﻿<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Main.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeaderPlaceHolder" runat="server">
    <link href="<%= this.Url.Content("~/content/mapplaces.css") %>" rel="Stylesheet" type="text/css" />
    <link href="<%= this.Url.Content("~/content/jqui/css/jquery.ui.all.css") %>" rel="Stylesheet" type="text/css" />

    <script type="text/javascript" language="javascript" src="<%=this.Url.Content("~/content/jqui/jquery.ui.core.js") %>"></script>

    <script type="text/javascript" language="javascript" src="<%=this.Url.Content("~/content/jqui/jquery.ui.widget.js") %>"></script>

    <script type="text/javascript" language="javascript" src="<%=this.Url.Content("~/content/jqui/jquery.ui.position.js") %>"></script>

    <script type="text/javascript" language="javascript" src="<%=this.Url.Content("~/content/jqui/jquery.ui.autocomplete.js") %>"></script>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>

    <script type="text/javascript" language="javascript" src="<%=this.Url.Content("~/content/gmap.js") %>"></script>

    <script type="text/javascript">
        var all_rs = [];
    </script>

    <script type="text/javascript" language="javascript" src="<%=this.Url.Content("~/caches/base_info/all_rs.js?rd="+new Random().NextDouble()) %>"></script>

    <script type="text/javascript" language="javascript" src="<%=this.Url.Content("~/caches/base_info/cityinfo.js?rd="+new Random().NextDouble()) %>"></script>

    <script type="text/javascript" language="javascript" src="<%=this.Url.Content("~/caches/user_focus/"+BancheStaff.CurrentStaffID+".js?rd="+new Random().NextDouble()) %>"></script>

    <script type="text/javascript">
        var user_focus_url = '<%=this.Url.Content("~/caches/user_focus/"+BancheStaff.CurrentStaffID+".js") %>';
        var dircache = '<%=this.Url.Content("~/caches/") %>';
        var wucha = 0.01; //经纬度的误差范围 0.01约1000米
        var myLatlng = new google.maps.LatLng(22.53969424532717, 113.93559741973877);
        var marker;
        var map;
        //
        var searchCircle;
        var matchedStationWithSearched = [];
        var localSearchResult = [];
        var mapSearchResult = [];
        var gInfoWindow;
        // Create our "tiny" marker icon
        var gYellowIcon = new google.maps.MarkerImage(
              '<%=this.Url.Content("~/Content/Images/mm_20_yellow.png") %>',
              new google.maps.Size(24, 40),
              new google.maps.Point(0, 0),
              new google.maps.Point(12, 40),
              new google.maps.Size(24, 40));
        //路线（直线，当绘制沿路的线失败后绘制直线）
        var routeLine; //绘制的直线
        var routeLineStations = []; //整条路线上的站点
        var waypts = [];
        //绘制路线(沿实际路线绘制)
        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();

        //初始化地图
        function initialize() {
            var mapOptions = {
                zoom: 15,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: myLatlng
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            // Create one InfoWindow to open when a marker is clicked.
            gInfoWindow = new google.maps.InfoWindow();
            google.maps.event.addListener(gInfoWindow, 'closeclick', function() {
                unselectAllMarkers();
            });

            marker = new google.maps.Marker({
                title: "深圳腾讯大厦",
                map: map,
                draggable: false,
                animation: google.maps.Animation.DROP,
                position: myLatlng
            });
        }

        //通过站点ID显示信息
        function showInfoBySid(sid) {
            var gmark;
            for (var i = 0; routeLineStations != null && i < routeLineStations.length; i++) {
                if (routeLineStations[i].result_.sid == sid) {
                    gmark = routeLineStations[i];
                    break;
                }
            }
            if (gmark) {
                gmark.select();
            }
            return false;
        }

        //通过站点ID和名称显示站点的刷卡人员列表
        function showEmpList(sid, sname) {
            var liststr = '';
            try {
                var silist = $.ajax({
                    url: dircache + 'gps_emplist/' + sid + '.js?rnd=' + Math.random(),
                    async: false,
                    dataType: "json"
                }).responseText;
                silist = eval("(" + silist + ")");
                liststr = silist.emps[0];
                for (var i = 1; i < silist.emps.length; i++) {
                    liststr += (i % 4 == 0 ? "" : ",") + silist.emps[i];
                    if (i % 4 == 3)
                        liststr += "<br/>";
                }
            } catch (ex) { }
            var emplist = '<div><h3>' + sname + '-人员列表</h3><div>' +
                '注：此列表中列出的是近几天每天都乘坐此班车的员工。<br/>' +
                liststr +
                '</div><a href="#" onclick="return showInfoBySid(\'' + sid + '\');">返回</a></div>';
            gInfoWindow.setContent(emplist);
            var gmark;
            for (var i = 0; i < matchedStationWithSearched.length; i++) {
                if (matchedStationWithSearched[i].sid == sid) {
                    gmark = matchedStationWithSearched[i].marker();
                    break;
                }
            }
            gInfoWindow.open(map, gmark);
            return false;
        }

        //PAGE LOAD
        $(function() {
            initialize();
            var input = document.getElementById('gmapsearch');
            var autocomplete = new google.maps.places.Autocomplete(input);

            autocomplete.bindTo('bounds', map);

            //autocomplte for search
            $("#txtSearch").autocomplete({
                source: function(request, response) {
                    searchSourceCallback(request, response);
                },
                minLength: 1,
                select: function(event, ui) {
                    searchSelectCallback(event, ui);
                }
            });
            //载入关注
            loadFocus();
            //载入城市
            loadCity();
        });

        //绘制查找的圆形区域
        function drawSearchCircle(lon, lat) {
            if (searchCircle != null) {
                searchCircle.setCenter(new google.maps.LatLng(lat, lon));
            } else {
                var populationOptions = {
                    strokeColor: "#FF0000",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#FF0000",
                    fillOpacity: 0.35,
                    map: map,
                    center: new google.maps.LatLng(lat, lon),
                    radius: wucha * 110000
                };
                searchCircle = new google.maps.Circle(populationOptions);
            }
        }
        //autocomplete select call back
        function searchSelectCallback(e, it) {
            //alert(it.item.label + "," + it.item.lon);
            //清理上一次的结果
            $("#divSearchResult").html("");
            showRouteInfo('');
            unselectAllMarkers();
            clearMatchedStations();
            clearRouteLineAndItsStations();
            if (gInfoWindow)
                gInfoWindow.close();
            var lon = it.item.lon;
            var lat = it.item.lat;
            drawSearchCircle(lon, lat);
            setMapCenter(lon, lat);
            if (all_rs && all_rs.length > 0) {
                for (var i = 0; i < all_rs.length; i++) {
                    var it = all_rs[i];
                    if (Math.sqrt(Math.pow(it.lon - lon, 2) + Math.pow(it.lat - lat, 2)) < wucha) {
                        var ss = new SearchMapResult(all_rs[i], 1, true);
                        matchedStationWithSearched.push(ss);
                    }
                }
            }
        }

        //autocomplete source callback
        function searchSourceCallback(request, response) {
            doSearch(response);
        }
        //点击搜索按钮
        function preSearch() {
            var query = $("#txtSearch").val();
            if ($.trim(query) == '') {
                InfoTip.showMessage("搜索条件不能为空！", 2);
                return;
            }
            $("#txtSearch").autocomplete("search");
            $("#txtSearch").focus();
        }
        //执行搜索本地（JS）和地图
        function doSearch(res) {
            var query = $("#txtSearch").val();
            // 清理之前的搜索信息
            localSearchResult = [];
            //开始查找本地
            var searched = searchLocalStations(query);
            //开始查找地图
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'address': query }, function(results, status) {
                searchMap(results, status, res);
            });
        }
        //查找本地（JS）
        function searchLocalStations(q) {
            localSearchResult = [];
            if (all_rs && all_rs.length > 0) {
                var cname = $("#selCity option[selected='selected']").text();
                if (cname == null || cname == 'undefined' || cname == '')
                    cname = '';
                for (var i = 0; i < all_rs.length; i++) {
                    if ((cname == '' || all_rs[i].cname == cname) && all_rs[i].sname.indexOf(q) >= 0) {
                        localSearchResult.push({
                            label: '[班车站点]' + all_rs[i].sname,
                            value: all_rs[i].sname,
                            isStation: 1,
                            lon: all_rs[i].lon,
                            lat: all_rs[i].lat
                        });
                    }
                }
            }
        }

        //查找地图
        function searchMap(results, status, res) {
            mapSearchResult = [];
            if (status == google.maps.GeocoderStatus.OK) {
                for (var i = 0; i < results.length; i++) {
                    var addr = results[i].formatted_address;
                    if (addr.indexOf('中国') == 0)
                        addr = addr.substr(2);
                    var idxSpace = addr.indexOf(' ');
                    addr = idxSpace > 0 ? addr.substr(0, idxSpace) : addr;
                    mapSearchResult.push({
                        label: addr,
                        value: addr,
                        isStation: 0,
                        lon: results[i].geometry.location.lng(),
                        lat: results[i].geometry.location.lat()
                    });
                }
            } else {
            }
            var sr = [];
            var i = 0;
            for (i = 0; i < localSearchResult.length; i++)
                sr.push(localSearchResult[i]);
            for (i = 0; i < mapSearchResult.length; i++)
                sr.push(mapSearchResult[i]);
            res(sr);
            if (sr.length <= 0)
                InfoTip.showMessage("没有数据，请修改搜索条件！", 2);
        }

        //取消地图标注点的选中
        function unselectAllMarkers() {
            for (var i = 0; matchedStationWithSearched != null && i < matchedStationWithSearched.length; i++) {
                matchedStationWithSearched[i].unselect();
            }
        }

        //在地图上清除匹配的到的站点
        function clearMatchedStations() {
            if (matchedStationWithSearched && matchedStationWithSearched.length > 0) {
                for (var i = 0; i < matchedStationWithSearched.length; i++)
                    matchedStationWithSearched[i].marker().setMap(null);
            }
            matchedStationWithSearched = [];
        }
        //在地图上清除路线及其站点
        function clearRouteLineAndItsStations() {
            var i = 0;
            if (routeLine != null) {
                routeLine.setMap(null);
            }
            if (routeLineStations && routeLineStations.length > 0) {
                for (i = 0; i < routeLineStations.length; i++) {
                    routeLineStations[i].marker().setMap(null);
                }
                routeLineStations = [];
            }
            if (directionsDisplay) {
                directionsDisplay.setMap(null);
            }
        }
        //载入关注路线
        function loadFocus() {
            var container = $("#ul_focus");
            container.html("");
            if (typeof (USER_FOCUS) != "undefined" && USER_FOCUS.length > 0) {
                var counter = 0;

                $.each(USER_FOCUS, function(n, o) {
                    if (counter++ > 4)
                        return;
                    if (o.StationName) {
                        var html = '<span><a href="javascript:drawLineByFocus(\'' + o.StationID + '\',\'' + o.RouteID + '\');">' + o.StationName + '</a>&nbsp;&nbsp;</span>';
                        container.append(html);
                    }
                });
            }
            else {
                //container.append("暂无关注路线(站点)。");
            }
        }
        //根据关注 站点 绘制路线
        function drawLineByFocus(sid, rid) {
            var ri = $.ajax({
                url: dircache + 'base_info/' + rid + '.js?rnd=' + Math.random(),
                async: false,
                dataType: "json"
            }).responseText;
            try {
                ri = eval("(" + ri + ")");
            } catch (ex) { ri = null; return; }
            drawRouteLineAndInfos(ri);
            if (routeLineStations != null && routeLineStations.length > 0) {
                var i = 0;
                for (i = 0; i < routeLineStations.length; i++) {
                    if (routeLineStations[i].result_ != null && routeLineStations[i].result_.sid == sid) {
                        routeLineStations[i].select();
                        break;
                    }
                }
            }
        }
        //载入城市
        function loadCity() {
            var container = $("#selCity");
            if (typeof (CITY_INFO) != "undefined" && CITY_INFO.length > 0) {
                $.each(CITY_INFO, function(n, o) {
                    container.append('<option value="' + o.CityId + '">' + o.CityName + '</option>');
                });
            }
        }
        //设置地图下方的路线信息
        function showRouteInfo(info0) {
            $('#divRouteInfo').html(info0);
        }
        function drawRouteLineAndInfos(ri) {
            //显示路线信息
            var rihtml = '';
            try {
                rihtml = '<div class=texttitle>' + ri.rname + ' -- ' + ri.rt + '</div>';
            } catch (ex) { rihtml = ''; }
            var shtml = '<div class=routetdtl>';
            try {
                var i = 0;
                if (ri.ss && ri.ss.length > 0) {
                    shtml += '<a href="#" onclick="return setStationMapCenter(' + i + ',\'' + ri.ss[0].lon + '\',\'' + ri.ss[0].lat + '\');">' + ri.ss[0].sname + '(' + ri.ss[0].arrtime + ')' + '</a>';
                    for (i = 1; i < ri.ss.length; i++) {
                        shtml += ' - <a href="#" onclick="return setStationMapCenter(' + i + ',\'' + ri.ss[i].lon + '\',\'' + ri.ss[i].lat + '\');">' + ri.ss[i].sname + '(' + ri.ss[i].arrtime + ')' + '</a>';
                    }
                }
            } catch (ex) { shtml = ''; }
            shtml += '</div>';
            var ps = '0';
            if (ri != null && ri.ps != null)
                ps = ri.ps;
            var fzr = '暂无';
            if (ri != null && ri.fzr != null)
                fzr = ri.fzr;
            var otherhtml = '<div class=routeattachinfo> 可容纳 ' + ps + ' 人，每' + ri.ww + ' 运行<br/>负责人：' + fzr + '</div>';
            drawRouteLine(ri); //画出路线
            showRouteInfo(rihtml + shtml + otherhtml); //显示路线信息
        }
        //绘制路线在地图上
        function drawRouteLine(ri) {
            if (ri == null)
                return;
            clearRouteLineAndItsStations();
            routeLineStations = [];
            var i = 0;
            if (ri.ss && ri.ss.length > 0) {
                var lls = new google.maps.LatLng(ri.ss[i].lat, ri.ss[i].lon);
                var s;
                var allrsit = getAllRSItem(ri.ss[i].sid);
                if (allrsit) {
                    s = new SearchMapResult(allrsit, 2, false);
                    routeLineStations.push(s);
                }
                if (ri.ss.length > 1) {
                    waypts = [];
                    var lastIdx = ri.ss.length - 1;
                    for (i = 1; i < lastIdx; i++) {
                        allrsit = getAllRSItem(ri.ss[i].sid);
                        if (allrsit) {
                            s = new SearchMapResult(allrsit, 2, false);
                            routeLineStations.push(s);
                        }
                        var loc0 = new google.maps.LatLng(ri.ss[i].lat, ri.ss[i].lon);
                        waypts.push({ location: loc0, stopover: true });
                    }
                    var lle = new google.maps.LatLng(ri.ss[lastIdx].lat, ri.ss[lastIdx].lon);
                    allrsit = getAllRSItem(ri.ss[i].sid);
                    if (allrsit) {
                        s = new SearchMapResult(allrsit, 2, false);
                        routeLineStations.push(s);
                    }
                    drawRealRoute(lls, lle);
                }
            }
        }

        //绘制班车路线(沿实际路线)
        function drawRealRoute(s, e) {
            var start = s;
            var end = e;
            var request = {
                origin: start,
                destination: end,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsDisplay = new google.maps.DirectionsRenderer({ suppressMarkers: true, preserveViewport: false });
            directionsDisplay.setMap(map);
            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
                else {
                    directionsDisplay.setMap(null);
                    directionsDisplay = null;
                    var pts = [];
                    pts.push(s);
                    var i = 0;
                    for (i = 0; i < waypts.length; i++) {
                        pts.push(waypts[i].location);
                    }
                    pts.push(e);
                    var routeLine = new google.maps.Polyline({
                        path: pts,
                        strokeColor: "#0000FF",
                        strokeOpacity: 0.3,
                        strokeWeight: 5
                    });
                    routeLine.setMap(map);
                }
            });
        }

        //从all_rs中搜索匹配SID的项返回
        function getAllRSItem(sid) {
            var m;
            if (all_rs && all_rs.length > 0) {
                for (var i = 0; i < all_rs.length; i++) {
                    if (all_rs[i].sid == sid) {
                        m = all_rs[i];
                        break;
                    }
                }
            }
            return m;
        }
        //发送到我的手机（路线ID，站点ID）
        function sendsms(rid, sid, sms0) {
            //alert(rid + "," + sid + "\r\n" + sms0);
            sendToMyPhone(rid);
        }
        //发送回调,重新载入
        function onfocusStation(result) {
            $.get(user_focus_url + "?tick=" + getTimeTick(), function(data) {
                if (data) {
                    loadFocus();
                }
            });
        }
        //关注此站点
        function focusStation(rid, sid) {
            newFocus(sid, onfocusStation);
        }
        //设置路线的站点地图居中
        function setStationMapCenter(sidx, lon, lat) {
            try {
                map.setCenter(new google.maps.LatLng(lat, lon));
                routeLineStations[sidx].select();
            } catch (ex) { }
        }
        //设置地图中心点
        function setMapCenter(lon, lat) {
            try {
                map.setCenter(new google.maps.LatLng(lat, lon));
            } catch (ex) { }
        }        
    </script>

</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="mainFrameTop" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainContainerPlaceHolder" runat="server">
    <div class="main_left" style="width: 910px;">
        <div class="text_body" style="margin-bottom: 10px;">
            <div class="text_title">
                <span></span>搜索班车路线、站点</div>
            <div class="text_cont" style="text-align: left; padding-top: 5px; padding-left: 15px;">
                <div id="ul_focus" style="text-align: left;">
                </div>
                <div style="padding-top: 5px; line-height: 20px; vertical-align: top;">
                    <select id="selCity" style="width: 100px;">
                    </select>
                    <input id="txtSearch" type="text" class="form_text" style="width: 440px;" value="世界之窗站" />
                    <input id="btnSearch" class="form_bot" type="submit" value="搜 索" onclick="return preSearch();" />
                </div>
            </div>
            <div class="text_bot">
                <span></span>
            </div>
        </div>
        <div class="text_body" style="margin-bottom: 10px;">
            <div class="text_top">
                <span></span>
            </div>
            <div class="text_cont" style="text-align: center; padding-top: 5px; position: relative;">
                <div style="position: relative; z-index: 100; height: 0px;">
                </div>
                <div class="search_bar" id="map_search">
                    <input id="gmapsearch" type="text" class="search_text" />
                </div>
                <div id="map_canvas" style="width: 887px; height: 490px; text-align: left;">
                    GoogleMap
                </div>
            </div>
            <div class="text_bot">
                <span></span>
            </div>
        </div>
        <div class="text_body" style="margin-bottom: 10px; display: none;">
            <div class="text_top">
                <span></span>
            </div>
            <div class="text_cont" style="text-align: center; padding-top: 15px;">
                <div id="divRouteInfo" class="td_routedtl">
                    路线信息:无</div>
            </div>
            <div class="text_bot">
                <span></span>
            </div>
        </div>
    </div>
    <div class="main_left" style="width: 910px; display: none;">
        <div class="text_body">
            <div class="text_title">
                <span></span><a href="<%=this.Url.Content("~/Focus") %>"></a>搜索到的站点列表</div>
            <div class="text_cont" style="overflow: auto;">
                <ul id="divSearchResult" class="right_time" style="overflow: auto;">
                </ul>
            </div>
            <div class="text_bot">
                <span></span>
            </div>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="mainFrameBottom" runat="server">
</asp:Content>
